<?php


namespace app\app\controller;


use think\Db;

class Vod extends Base
{
    public $jiexiArray = ['qq','qiyi','youku','mgtv'];
    public $jiexiAppUrl="http://www.jingyuxitong.com/api/?type=app&key=LjEdBZv6qtLYe5nZMC&url=";
    public $jiexiJsonUrl="http://www.jingyuxitong.com/api/?key=LjEdBZv6qtLYe5nZMC&url=";
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $input = input();
//            dump($input);
        $where = $input['where'];
        if (isset($where['type_id']) && $where['type_id'] > 0) {
            $where['type_id|type_id_1'] = $where['type_id'];
        }
        unset($where['type_id']);
        if (isset($where['vod_name']) && !isset($where['keyword'])) {
            $where['vod_name'] = ['like', '%' . $where['vod_name'] . '%'];
        } elseif (isset($where['keyword'])) {
            $where['vod_name|vod_actor'] = ['like', '%' . $where['keyword'] . '%'];
            unset($where['keyword']);
        }
        if (isset($where['vod_level'])) {
            $where['vod_level'] = ['in', $where['vod_level']];
        }
        if (isset($where['vod_class'])) {
            $where['vod_class'] = ['like', '%' . $where['vod_class'] . '%'];
        }
        if (isset($where['vod_area'])) {
            $where['vod_area'] = ['like', '%' . $where['vod_area'] . '%'];
        }

        $where['vod_time'] = ['>', 0];
        if (empty($where['vod_name|vod_actor'])) {
            $whereRaw = 'CONVERT(vod_year,DECIMAL) <= ' . date('Y');
        } else {
            $whereRaw = ' 1=1';
        }
        $order = $input['order'];
        $page = $input['page'] < 1 ? 1 : $input['page'];
        $limit = (intval($input['limit']) > 1) ? intval($input['limit']) : 20;
        $start = 0;
        $field = 'vod_name,vod_year,image_down,vod_pic,vod_pic_thumb,vod_time,vod_area,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level';
        $addition = 0;
        $totalshow = 1;
        $order = " CONVERT(vod_year,DECIMAL) desc,vod_time desc,vod_id desc";
        // $playerNames = getPlayerNames();
        // usort($playerNames,function ($a,$b){
        //     return $a['sort']<$b['sort']?-1:1;
        // });
//            $data = [];
//             foreach ($playerNames as $key=>$playerName) {
// //                dump($key);
//                 if (count($data) > 0) {
//                     break;
//                 } else {
        // $where['vod_play_from']=['like','%'.$playerName['from'].'%'];
        $list = listAppData($where, $order, $page, $limit, $start, $field, $addition, $totalshow, $whereRaw);
//            $data = array_merge($data, $list['list']);
        //     }
        // }
//            dump($list);exit;
        $this->success('获取成功', $list);
    }


    public function detailcachetwo()
    {
        $id = input('vod_id', 0, 'intval');
        if ($id < 1) {
            $this->error('数据有误！');
        }
        $time = time();
        $input = input();
        if (!empty($input['app_id'])) {
            \db('user_history')->insert(
                [
                    'device_id' => $input['device_id'],
                    'device_name' => $input['device_name'],
                    'app_id' => $input['app_id'],
                    'app_name' => $input['app_name'],
                    'vod_id' => $input['vod_id'],
                    'system_type' => $input['system_type'],
                    'time_added' => $time,
                    'push_id' => $input['pageParam.pushId'] ?: 0
                ]
            );
        }
        $data = cache('VOD_DETAIL_INFO_' . $id);
        if (empty($data)) {
            $data = getVodByIdDetailtwo($id);
            if ($data['image_down'] > 0) {
                $data['vod_pic'] = "http://7dfjeh.aojiasen.cn/cover/" . $data['vod_id'] . '.jpg';
            }
            $data['share_image'] = \db('config')->where('name', 'share_image')->value('value');
            $data['player_image'] = \db('config')->where('name', 'player_image')->value('value');
            cache('VOD_DETAIL_INFO_' . $id, $data, 300);
        }
        $host = request()->host();
        if ($host == "www.hawen.online") {
            $data['playNames'] = [];
            $data["vod_play_url"] = '';
            $data["vod_play_from"] = '';
            $data['vod_blurb'] = '安卓用户点击右上角分享下载新版本 [视频秒播];<br/>安卓用户点击右上角分享下载新版本 [视频秒播];';
            $data['vod_content'] = '安卓用户点击右上角分享下载新版本 [视频秒播];<br/>安卓用户点击右上角分享下载新版本 [视频秒播];';
            $data['fileurl'] = [];
        }

        if (!empty($input['app_id'])) {

            $inputArray = [
                'app_id' => $input['app_id'],
                'app_name' => $input['app_name'],
                'key_name' => $input['keyname'],
                'device_id' => $input['device_id'],
                'device_name' => $input['device_name'],
                'app_version' => $input['app_version'],
                'vod_id' => $input['vod_id'],
                'vod_name' => $data['vod_name'],
                'adtype' => '-2',
                'memo' => '获取详情',
                'ctime' => $time
            ];
            db('openadlog')->insertGetId($inputArray);
        }
        $this->success('获取成功', $data);
    }

    public function detailcachetwonew()
    {
        $host = request()->host();
        $appUrl = input('appUrl','','trim');
        $id = input('vod_id', 0, 'intval');
        if ($id < 1) {
            $this->error('数据有误！');
        }
        $time = time();
        $input = input();
        if ($host == "www.xdhej.xyz") {//人人影迷
            $data['playNames'] = [];
            $data["vod_play_url"] = '';
            $data["vod_play_from"] = '';
            $data['vod_blurb'] = '点击右上角分享下载新版本 [视频秒播];<br/>点击右上角分享下载新版本 [视频秒播];';
            $data['vod_content'] = '点击右上角分享下载新版本 [视频秒播];<br/>点击右上角分享下载新版本 [视频秒播];';
            $data['fileurl'] = [
                [
                    'sort' => 0,
                    "len" => 0,
                    'from' => [
                        'from' => '1',
                        'sort' => 0,
                        'show' => '1',
                        'id' => '1'
                    ],
                    'playlist' => []
                ]
            ];

            $this->success('获取成功', $data);
        }
        $data = cache('VOD_DETAIL_NEW_INFO_'.$appUrl."_" . request()->host() ."_". $id);
        if (empty($data)) {
            $data = Db::name('Vod')->field('vod_id,vod_name,vod_pic,vod_play_from,vod_play_url,vod_blurb,vod_content,vod_time,vod_actor,vod_actor,is_cache,vod_area,vod_pic_thumb,vod_pic_slide,vod_remarks')->where('vod_id', $id)->where('vod_status', 1)->find();
            if (empty($data)) {
                $data = [];
            } else {
                $data['parseUrl'] = "http://www.jingyuxitong.com/api/?key=LjEdBZv6qtLYe5nZMC&url=";
                $data['vod_time'] = date('Y-m-d H:i', $data['vod_time']);
                $data['vod_pic'] = strpos($data['vod_pic'], 'http') === 0 ? $data['vod_pic'] : (request()->domain() . '/' . $data['vod_pic']);
                $data['vod_pic_thumb'] = $data['vod_pic_thumb'] ? (strpos(
                    $data['vod_pic_thumb'],
                    'http'
                ) === 0 ? $data['vod_pic_thumb'] : (request()->domain() . '/' . $data['vod_pic_thumb'])) : '';
                $v['vod_pic_slide'] = $data['vod_pic_slide'] ? (strpos(
                    $data['vod_pic_slide'],
                    'http'
                ) === 0 ? $data['vod_pic_slide'] : (request()->domain() . '/' . $data['vod_pic_slide'])) : '';

                $data['vod_content'] = strip_tags($data['vod_content']);
//                $data['vod_actor'] = explode(',', $data['vod_actor']);
                $data['ism3u8'] = 1;
                $data['fileurl'] = [];
                $sortOrder = 'asc';
                if (in_array($data['type_id_1'], [3]) || in_array($data['type_id'], [3])) {
                    $sortOrder = 'desc';
                }
                $ttCache = \db('m3u8_cache_other')->fieldRaw('sort as `index`, `value`  as url, `key` as name,1 as ism3u8 ')->where('from', 'tiantang')->where('vod_id', $data['vod_id'])->where('is_need_deal', 0)->order('sort', $sortOrder)->select();
                if (!empty($ttCache)) {
//                    foreach ($ttCache as $key => &$ttCachejuji) {
//                        $ttCachejuji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 0,
                        "len" => count($ttCache),
                        'from' => [
                            'from' => '天堂网',
                            'sort' => 0,
                            'show' => '天堂网',
                            'id' => 'tiantang'
                        ],
                        'playlist' => $ttCache
                    ];
                }


                $bjCache = \db('m3u8_cache_bj')->fieldRaw('sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $data['vod_id'])->order('sort', $sortOrder)->select();
                if (!empty($bjCache)) {
//                    foreach ($bjCache as $key => &$bjCachejuji) {
//                        $bjCachejuji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 1,
                        "len" => count($bjCache),
                        'from' => [
                            'from' => '八戒网',
                            'sort' => 1,
                            'show' => '八戒网',
                            'id' => 'localbj'
                        ],
                        'playlist' => $bjCache
                    ];
                }

                $localCache = \db('m3u8_cache')->fieldRaw('sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $data['vod_id'])->order('sort', $sortOrder)->select();
                if (!empty($localCache)) {
//                    foreach ($localCache as $key => &$juji) {
//                        $juji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 2,
                        "len" => count($localCache),
                        'from' => [
                            'from' => '最大网',
                            'sort' => 2,
                            'show' => '最大网',
                            'id' => 'local'
                        ],
                        'playlist' => $localCache
                    ];
                }



                $playNames = getPlayerNames();
                $playGroups = [];
                $playfroms = explode('$$$', $data['vod_play_from']);
                unset($data['vod_play_from']);
                $playNotes = explode('$$$', $data['vod_play_note']);
                unset($data['vod_play_note']);
                unset($data['vod_play_server']);
                $playUrls = explode('$$$', $data['vod_play_url']);
                unset($data['vod_play_url']);
                foreach ($playUrls as $key => $jujiurl) {
                    //解析url
                    $jujis = explode('#', $jujiurl);
                    $playList = [];
                    $needParse = false;
                    $changeUrlToAppUrl=false;
                    if(in_array($playNames[$playfroms[$key]]['from'],$this->jiexiArray)){
                        $needParse = true;
                    }
                    if($needParse === true && is_old_host()){
                        continue;
                    }
                    if($needParse===true && $appUrl==='appUrl'){
                        $changeUrlToAppUrl=true;
                    }
                    foreach ($jujis as $index => $juji) {
                        list($name, $url) = explode('$', $juji);
                         if($changeUrlToAppUrl){
                             $url=$this->jiexiAppUrl.urlencode($url);
                             $needParse = false;
                         }
                        $playList[] = [
                            'name' => $name,
                            'url' => $url,
                            'index' => $index,
                            'need_parse'=>$needParse===true?1:0
                        ];
                    }
                    $playGroups[$key] = [
                        'playlist' => $playList,
                        'from' => [
                            'from' => $playNames[$playfroms[$key]]['from'],
                            'sort' => $playNames[$playfroms[$key]]['sort'],
                            'show' => $playNames[$playfroms[$key]]['show'],
                            'id' => $playNames[$playfroms[$key]]['id'],
                            'need_parse'=>$needParse===true?1:0
                        ],
                        'len' => count($playList)
                    ];
                }
                if (count($playGroups) > 1) {
                    //按序号排序
                    usort($playGroups, function ($a, $b) {
                        if ($a['len'] < $b['len']) {
                            return 1;
                        } elseif ($a['len'] == $b['len']) {
                            if ($a['from']['sort'] > $b['from']['sort']) {
                                return 1;
                            } else {
                                return 0;
                            }
                        } else
                            return -1;

                    });

                }
                if (empty($data['fileurl'])) {
                    $data['fileurl'] = $playGroups;
                }else{
                    $newFileUrl =[];
                    foreach ($playGroups as $playItem){
                        if(in_array($playItem['from']['from'],$this->jiexiArray)){
                            $newFileUrl[]=$playItem;
                        }
                    }
                    $data['fileurl']=array_merge($newFileUrl,$data['fileurl']);
                }
            }

            if (!empty($data['fileurl'])) {
                if (count($data['fileurl']) > 1) {
                    usort($data['fileurl'], function ($a, $b) {
                        if ($a['len'] < $b['len']) {
                            return 1;
                        } elseif ($a['len'] == $b['len']) {
                            if ($a['from']['sort'] > $b['from']['sort']) {
                                return 1;
                            } else {
                                return 0;
                            }
                        } else
                            return -1;

                    });
                }
            }

            if ($data['image_down'] > 0) {
                $data['vod_pic'] = "http://7dfjeh.aojiasen.cn/cover/" . $data['vod_id'] . '.jpg';
            }
            $data['share_image'] = \db('config')->where('name', 'share_image')->value('value');
            $data['player_image'] = \db('config')->where('name', 'player_image')->value('value');
            cache('VOD_DETAIL_NEW_INFO_'.$appUrl."_" . request()->host() ."_". $id, $data, 300);
        }

        if (!empty($input['app_id'])) {
            \db('user_history')->insert(
                [
                    'device_id' => $input['device_id'],
                    'device_name' => $input['device_name'],
                    'app_id' => $input['app_id'],
                    'app_name' => $input['app_name'],
                    'vod_id' => $input['vod_id'],
                    'system_type' => $input['system_type'],
                    'time_added' => $time,
                    'push_id' => $input['pageParam.pushId'] ?: 0
                ]
            );
            $inputArray = [
                'app_id' => $input['app_id'],
                'app_name' => $input['app_name'],
                'key_name' => $input['keyname'],
                'device_id' => $input['device_id'],
                'device_name' => $input['device_name'],
                'app_version' => $input['app_version'],
                'vod_id' => $input['vod_id'],
                'vod_name' => $data['vod_name'],
                'adtype' => '-2',
                'memo' => '获取详情',
                'ctime' => $time
            ];
            db('openadlog')->insertGetId($inputArray);
        }
        $this->success('获取成功', $data);
    }

    public function downloadM3u8()
    {
        $id = input('vod_id', 0, 'intval');
        if ($id < 1) {
            $this->error('数据有误！');
        }

        $data = cache('download_m3u8_cache_vod_' . $id);
        if (empty($data)) {
            //检查是否存在天堂源

            $data = Db::name('Vod')->field('vod_id,type_id_1,type_id,vod_name,vod_play_from,vod_play_url')->where('vod_id', $id)->where('vod_status', 1)->find();

            if (empty($data)) {
                $data = [];
            } else {
                $data['ism3u8'] = 1;
                $data['fileurl'] = [];
                $sortOrder = 'asc';
                if (in_array($data['type_id_1'], [3]) || in_array($data['type_id'], [3])) {
                    $sortOrder = 'desc';
                }
//                $ttCache = \db('m3u8_cache_other')->fieldRaw('sort as `index`, `value`  as url, `key` as name,1 as ism3u8 ')->where('from', 'tiantang')->where('vod_id', $data['vod_id'])->where('is_need_deal', 0)->order('sort', $sortOrder)->select();
                $playNames = getPlayerNames();
                $playGroups = [];
                $playfroms = explode('$$$', $data['vod_play_from']);
                $playNotes = explode('$$$', $data['vod_play_note']);
                $playUrls = explode('$$$', $data['vod_play_url']);
                foreach ($playUrls as $key => $jujiurl) {
                    //解析url
                    $jujis = explode('#', $jujiurl);
                    $playList = [];
                    foreach ($jujis as $juji) {
                        list($name, $url) = explode('$', $juji);
                        $playList[] = [
                            'name' => $name,
                            'url' => $url,
                        ];
                    }
                    $playGroups[$key] = [
                        'playlist' => $playList,
                        'from' => [
                            'from' => $playNames[$playfroms[$key]]['from'],
                            'sort' => $playNames[$playfroms[$key]]['sort'],
                            'show' => $playNames[$playfroms[$key]]['show'],
                            'id' => $playNames[$playfroms[$key]]['id']
                        ],
                        'len' => count($playList)
                    ];
                }
                if (count($playGroups) > 1) {
                    //按序号排序
                    usort($playGroups, function ($a, $b) {
                        if ($a['len'] < $b['len']) {
                            return 1;
                        } elseif ($a['len'] == $b['len']) {
                            if ($a['from']['sort'] > $b['from']['sort']) {
                                return 1;
                            } else {
                                return 0;
                            }
                        } else
                            return -1;

                    });
                    if ($playGroups[0]['from']['from'] == 'bjm3u8') {
                        if ($playGroups[0]['len'] == $playGroups[1]['len']) {
                            unset($playGroups[0]);
                        }
                    }
                    $m3u8List = array_shift($playGroups);
                    $m3u8List = $m3u8List['playlist'];
                } else {
                    $m3u8List = $playGroups[0]['playlist'];
                }
//                $ttCacheLength = count($ttCache);
//                $m3u8ListLength = count($m3u8List);
//                dump($m3u8List);
//                dump($ttCache);
//                if($ttCacheLength>0) {
////                    if ($ttCacheLength < $m3u8ListLength) {
//                        foreach ($ttCache as $key => $item) {
//                            $item['url']=parseurl($item['url']);
//                            $m3u8List[$key] = $item;
//                        }
////                    } else {
////                        $m3u8List = $ttCache;
////                    }
//                }

                $data['fileurl'] = $m3u8List;
                unset($data['vod_play_from']);
                unset($data['vod_play_note']);
                unset($data['vod_play_server']);
                unset($data['vod_play_url']);
            }
            cache('download_m3u8_cache_vod_' . $id, $data, 3600);

        }
        $this->success('获取成功', $data);
    }


    public function getRelVod()
    {
        $id = input('vod_id', 0, 'intval');
        if ($id < 1) {
            $this->error('数据有误');
        }

        $lp = [
            "num" => "6",
            "type" => "current",
            "paging" => "yes",
            "order" => "desc",
            "by" => "rnd",
            "id" => "vo",
            "key" => "key",
        ];
        $type_id = Db::name('Vod')->where('vod_id', $id)->where('vod_status', 1)->value('type_id');
        $input = [
            "page" => 1,
            "ajax" => 0,
            "tid" => $type_id,
            "mid" => 0,
            "rid" => 0,
            "pid" => 0,
            "sid" => 1,
            "nid" => 1,
            "uid" => 0,
            "level" => 0,
            "score" => 0,
            "limit" => 0,
            "id" => $id,
            "ids" => "",
            "wd" => "",
            "en" => "",
            "state" => "",
            "area" => "",
            "year" => '2019,' . date('Y'),
            "lang" => "",
            "letter" => "",
            "actor" => "",
            "director" => "",
            "tag" => "",
            "class" => "",
            "order" => "",
            "by" => "",
            "file" => "",
            "name" => "",
            "url" => "",
            "type" => "",
            "sex" => "",
            "version" => "",
            "blood" => "",
            "starsign" => "",
            "domain" => "",
        ];
        $data = getRecommandData($lp, $input);
        if (!empty($data)) {
            $this->success('获取到数据', ['list' => $data]);
        } else {
            $this->success('数据为空', []);
        }
    }

    public function repeatSearch()
    {
        $list = \db('vod')->group('vod_name')->where('vod_status', 1)->field(
            'count(vod_id) as num,vod_name'
        )->having('count(vod_id) >1')->paginate(200);
//            dump($list);exit;
        if ($list->isEmpty()) {
            return '已经处理完毕！';
        }
        $vodIds = [];
        foreach ($list as $item) {
            $data = \db('vod')->field('vod_id')->where('vod_name', $item['vod_name'])->order(
                'vod_time desc'
            )->select();
//                dump($data);
            for ($i = 1; $i < count($data); $i++) {
                $vodIds[] = $data[$i]['vod_id'];
            }
        }
//            dump($vodIds);
//            exit;
        $return = \db('vod')->whereIn('vod_id', $vodIds)->update(['vod_status' => 0]);
        $sql = \db('vod')->getLastSql();
        if ($return !== false) {
            $this->success('当前页面已处理完' . count($vodIds) . '条重复数据,请刷新页面继续处理下一条' . $sql);
        } else {
            return '处理失败' . $sql;
        }
    }

    public function getNoImgVod()
    {
        $list = \db('vod')->where('vod_pic', '')->field('vod_id,vod_name')->select();
        dump($list);
    }

    public function getBrokeImage()
    {
        $file = ROOT_PATH . "image.json";
        $filedata = file_get_contents($file);
        if (empty($filedata)) {
            $data = [];
        } else {
            $data = json_decode($filedata);
        }
        $list = \db('vod')->where('vod_pic', 'like', '%zy.yilans.net%')->field('vod_id,vod_name,vod_pic')->select();
        echo "done";
//            foreach ($list as $item){
//                echo "<a href='".$item['vod_pic']."'><img src='".$item['vod_pic']."' alt='无图' />".$item['vod_id']."-".$item['vod_name']."</a><br/>";
//            }
    }

    public function defaultXianlu()
    {
        $id = input('vod_id', 0, 'intval');
        $xianlu = input('xianlu', 0, 'intval');
        $v = Db::name('Vod')->where('vod_id', $id)->update(["vod_xianlu" => $xianlu]);
        if ($v) {
            $this->success('修改成功', $v);
        } else {
            $this->error(Db::name('Vod')->getlastsql());
        }
    }

    public function autom3u8()
    {
        //自动执行浏览器，每隔1小时自动抓一下后台
        $res = Db::query(
            "SELECT * FROM mac_vod WHERE is_cache = 1 and vod_time > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) order by vod_time asc"
        );

        if (!empty($res) && count($res) > 0) {
            foreach ($res as &$v2) {
                $v2['playNames'] = getPlayerNames();
            }
            $data['res'] = $res;
            $data['status'] = 1;
            echo json_encode($data);
        } else {
            $data['status'] = 0;
            echo json_encode($data);
        }
    }

    public function m3u8()
    {
        $type = input('type', '', 'trim');
        $id = input('xilie_id', 0, 'intval');
        if ($id < 1) {
            return json('系列id有误！');
        }
        switch ($type) {
            case 'tuijian':
                $model = \db('recommend')->where('id', $id);
                $modelVod = \db('recommend_vod')->where('recommend_id', $id)->order('sort_manual', 'asc');
                break;
            case 'explore':
                $model = \db('explore')->where('id', $id);
                $modelVod = \db('explore_vod')->where('explore_id', $id);
                break;
            default:
                return json('数据有误');
                break;
        }

        $xilieInfo = $model->find();

        if (empty($xilieInfo)) {
            return json('11数据有误！');
        }

        $ids = $modelVod->order('sort', 'asc')->order('time_added', 'desc')->order('id', 'desc')->limit(
            isset($xilieInfo['limit']) ? $xilieInfo['limit'] : 10
        )->column('vod_id');
        return json($ids);
    }

    public function recommendVod()
    {
        $list = cache('recommend_vod_top_20');
        if (empty($list)) {
            $where = [];
            $start = strtotime('yesterday');
            $end = strtotime('today');
            $where['uh.time_added'] = ['between', [$start, $end]];
            $list = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->whereNotIn('v.type_id', [41])->fieldRaw(
                'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time,count(1) as num,count(distinct device_id) as device_num'
            )->group('uh.vod_id')->where($where)->orderRaw('count(1) desc,count(distinct device_id) desc')->where(
                'v.vod_id',
                '>',
                0
            )->limit(20)->select();
            cache('recommend_vod_top_20', $list, strtotime('tomorrow') - time() + 1);
        }
        $this->success('获取成功', ['list' => $list]);
    }

    public function fixedSystemType()
    {
        $list = \db('user_history')->where('system_type is null')->select();
        if (count($list) > 0) {
            foreach ($list as $key => $item) {
                if (strpos($item['device_id'], '-') !== false) {
                    $item['system_type'] = 'ios';
                } else {
                    $item['system_type'] = 'android';
                }
                \db('user_history')->where('id', $item['id'])->update($item);
                dump('修复成功 - ' . ($key + 1));
            }
        } else {
            dump('没有需要处理的');
        }

        dump('处理完毕');
    }

    public function getAllRecommend()
    {
        $list = \db('recommend')->order('sort', 'asc')->select();

        $this->success('获取成功', $list);

    }

    public function getAllExplore()
    {
        $list = \db('explore')->order('sort', 'asc')->select();
        $typeList = \db('explore_type')->order('sort', 'asc')->select();
        $typeIds = array_column($typeList, 'id');

        foreach ($list as $item) {
            $index = array_search($item['type_id'], $typeIds);
            if (!isset($typeList[$index]['childs'])) {
                $typeList[$index]['childs'] = [];
            }

            $typeList[$index]['childs'][] = $item;
        }

        foreach ($typeList as &$typeItem) {
            if (!isset($typeItem['childs'])) {
                $typeItem['childs'] = [];
            }
        }


        $this->success('获取成功', $typeList);

    }

    public function updateXuanji()
    {
        $input = input();
        $time = time();
        if (empty($input['app_id'])) {
            $this->success('成功！');
        }
        $inputArray = [
            'app_id' => $input['app_id'],
            'key_name' => $input['keyname'],
            'device_id' => $input['device_id'],
            'vod_id' => $input['vod_id'],
            'xuanji' => $input['xuanji'],
            'yuan' => $input['yuan'],
            'adtype' => -2,
        ];
        if (!empty($input['shichang'])) {
            $inputArray['memo'] = '历史记录';
            $isExistLog = \db('openadlog')->where($inputArray)->find();
            if ($isExistLog) {
                $logId = $isExistLog['id'];
            }
            $inputArray['shichang'] = $input['shichang'];
        } else {
            $inputArray['memo'] = '选集播放';
        }
        $inputArray['vod_name'] = $input['vod_name'];
        $inputArray['app_name'] = $input['app_name'];
        $inputArray['device_name'] = $input['device_name'];
        $inputArray['app_version'] = $input['app_version'];
        $inputArray['ctime'] = $time;
        if (isset($logId)) {
            \db('openadlog')->where('id', $logId)->update($inputArray);
        } else {
            db('openadlog')->insertGetId($inputArray);
        }

        $this->success('添加成功！');
    }


    public function deleteDetailCache()
    {
        $vod_id = input('vod_id', 0, 'intval');
        if ($vod_id > 0) {
            cache('VOD_DETAIL_INFO_' . $vod_id, null);
            cache('VOD_DETAIL_NEW_INFO_' . $vod_id, null);
            cache('VOD_DETAIL_NEW_INFO_FROM_URL' . $vod_id, null);
            cache('VOD_DETAIL_NEW_INFO_TIANKONG15' . $vod_id, null);
        }
        $this->success('success');
    }


    public function vodDetail()
    {
        $id = input('vod_id', 0, 'intval');
        if ($id < 1) {
            $this->error('数据有误！');
        }
        $time = time();
        $input = input();
        if (empty($input['app_id']) || empty($input['device_id'])) {
            $this->error('基础数据有误！');
        }
        $data = cache('VOD_DETAIL_NEW_INFO_FROM_URL' . $id);
        if (empty($data)) {
            $data = Db::name('Vod')->field('vod_id,vod_name,vod_pic,vod_play_from,vod_play_url,vod_play_note,vod_blurb,vod_content,vod_time,vod_actor,vod_actor,is_cache,vod_area,vod_pic_thumb,vod_pic_slide,vod_remarks,vod_copyright')->where('vod_id', $id)->where('vod_status', 1)->find();
            if (empty($data)) {
                $data = [];
            } else {
                $data['vod_time'] = date('Y-m-d H:i', $data['vod_time']);
                $data['vod_pic'] = strpos($data['vod_pic'], 'http') === 0 ? $data['vod_pic'] : (request()->domain() . '/' . $data['vod_pic']);
                $data['vod_pic_thumb'] = $data['vod_pic_thumb'] ? (strpos(
                    $data['vod_pic_thumb'],
                    'http'
                ) === 0 ? $data['vod_pic_thumb'] : (request()->domain() . '/' . $data['vod_pic_thumb'])) : '';
                $v['vod_pic_slide'] = $data['vod_pic_slide'] ? (strpos(
                    $data['vod_pic_slide'],
                    'http'
                ) === 0 ? $data['vod_pic_slide'] : (request()->domain() . '/' . $data['vod_pic_slide'])) : '';

                $data['vod_content'] = strip_tags($data['vod_content']);
//                $data['vod_actor'] = explode(',', $data['vod_actor']);
                $data['ism3u8'] = 1;

                $playfroms = explode('$$$', $data['vod_play_from']);
                unset($data['vod_play_from']);

                $data['fileurl'] = [];
                $sortOrder = 'asc';
                if (in_array($data['type_id_1'], [3]) || in_array($data['type_id'], [3])) {
                    $sortOrder = 'desc';
                }
                $ttCache = \db('m3u8_cache_other')->fieldRaw('`from`,sort as `index`, `value`  as url, `key` as name,1 as ism3u8 ')->where('from', 'tiantang')->where('vod_id', $data['vod_id'])->where('is_need_deal', 0)->order('sort', $sortOrder)->fetchSql(true)->select();
                if (!empty($ttCache)) {
//                    foreach ($ttCache as $key => &$ttCachejuji) {
//                        $ttCachejuji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 0,
                        "len" => count($ttCache),
                        'from' => [
                            'from' => 'tiantang',
                            'sort' => 0,
                            'show' => '天堂影院',
                            'id' => 'tiantang'
                        ],
                        'url' => false,
                        'playlist' => $ttCache
                    ];
                }


                $bjCache = \db('m3u8_cache_bj')->fieldRaw('`from`, sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $data['vod_id'])->order('sort', $sortOrder)->select();
                if (!empty($bjCache)) {
//                    foreach ($bjCache as $key => &$bjCachejuji) {
//                        $bjCachejuji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 1,
                        "len" => count($bjCache),
                        'from' => [
                            'from' => $bjCache[0]['from'],
                            'sort' => 1,
                            'show' => getFromName($bjCache[0]['from']),
                            'id' => 'localbj'
                        ],
                        'url' => getFromVodurl($data['vod_play_note'], $bjCache[0]['from']),
                        'playlist' => $bjCache
                    ];
                }

                $localCache = \db('m3u8_cache')->fieldRaw('`from`,sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $data['vod_id'])->order('sort', $sortOrder)->select();
                if (!empty($localCache)) {
                    $data['fileurl'][] = [
                        'sort' => 2,
                        "len" => count($localCache),
                        'from' => [
                            'from' => $localCache[0]['from'],
                            'sort' => 2,
                            'show' => getFromName($localCache[0]['from']),
                            'id' => 'local',
                        ],
                        'url' => getFromVodurl($data['vod_play_note'], $localCache[0]['from']),
                        'playlist' => $localCache
                    ];
                }

                if (!empty($data['fileurl'])) {
                    // unset($data['vod_play_from']);
                    // unset($data['vod_play_server']);
                    // unset($data['vod_play_url']);
                    $fromVodUrl = false;
                    $fromName = false;
                    //处理天堂资源的url
                    foreach ($data['fileurl'] as &$fileUrl) {
                        if ($fileUrl['sort'] === 0) {
                            foreach ($playfroms as $playfrom) {
                                $fromVodUrl = getFromVodurl($data['vod_play_note'], $playfrom);
                                if ($fromVodUrl !== false) {
                                    $fromName = getFromName($playfrom);
                                    break;
                                }
                            }
                            if ($fromVodUrl !== false && $fromName !== false) {
                                $fileUrl['from']['from'] = $playfrom;
                                $fileUrl['from']['show'] = $fromName;
                                $fileUrl['url'] = $fromVodUrl;
                            }
                        }
                    }
                    if (count($data['fileurl']) > 1) {
                        usort($data['fileurl'], function ($a, $b) {
                            if ($a['len'] < $b['len']) {
                                return 1;
                            } elseif ($a['len'] == $b['len']) {
                                if ($a['from']['sort'] > $b['from']['sort']) {
                                    return 1;
                                } else {
                                    return 0;
                                }
                            } else
                                return -1;

                        });
                    }

                } else {

                    //调用原数据最大信息
                    $playNames = getPlayerNames();
                    $playGroups = [];
                    unset($data['vod_play_server']);
                    $playUrls = explode('$$$', $data['vod_play_url']);
                    unset($data['vod_play_url']);
                    foreach ($playUrls as $key => $jujiurl) {
                        //解析url
                        $jujis = explode('#', $jujiurl);
                        $playList = [];
                        foreach ($jujis as $juji) {
                            list($name, $url) = explode('$', $juji);
                            $playList[] = [
                                'name' => $name,
                                'url' => $url,
                            ];
                        }
                        $playGroups[$key] = [
                            'playlist' => $playList,
                            'from' => [
                                'from' => $playNames[$playfroms[$key]]['from'],
                                'sort' => $playNames[$playfroms[$key]]['sort'],
                                'show' => $playNames[$playfroms[$key]]['show'],
                                'id' => $playNames[$playfroms[$key]]['id']
                            ],
                            'url' => getFromVodurl($data['vod_play_note'], playNames[$playfroms[$key]]['from']),
                            'len' => count($playList)
                        ];
                    }
                    if (count($playGroups) > 1) {
                        //按序号排序
                        usort($playGroups, function ($a, $b) {
                            if ($a['len'] < $b['len']) {
                                return 1;
                            } elseif ($a['len'] == $b['len']) {
                                if ($a['from']['sort'] > $b['from']['sort']) {
                                    return 1;
                                } else {
                                    return 0;
                                }
                            } else
                                return -1;

                        });

                    }

                    $data['fileurl'] = $playGroups;
                }
            }


            if ($data['image_down'] > 0) {
                $data['vod_pic'] = "http://7dfjeh.aojiasen.cn/cover/" . $data['vod_id'] . '.jpg';
            }
            $data['share_image'] = \db('config')->where('name', 'share_image')->value('value');
            $data['player_image'] = \db('config')->where('name', 'player_image')->value('value');
            cache('VOD_DETAIL_NEW_INFO_FROM_URL' . $id, $data, 300);
        }


        \db('user_history')->insert(
            [
                'device_id' => $input['device_id'],
                'device_name' => $input['device_name'],
                'app_id' => $input['app_id'],
                'app_name' => $input['app_name'],
                'vod_id' => $input['vod_id'],
                'system_type' => $input['system_type'],
                'time_added' => $time,
                'push_id' => $input['pageParam.pushId'] ?: 0
            ]
        );
        $inputArray = [
            'app_id' => $input['app_id'],
            'app_name' => $input['app_name'],
            'key_name' => $input['keyname'],
            'device_id' => $input['device_id'],
            'device_name' => $input['device_name'],
            'app_version' => $input['app_version'],
            'vod_id' => $input['vod_id'],
            'vod_name' => $data['vod_name'],
            'adtype' => '-2',
            'memo' => '获取详情',
            'ctime' => $time
        ];
        db('openadlog')->insertGetId($inputArray);
        $this->success('获取成功', $data);
    }

}